﻿using BJoin.Common;
using FluentValidation;
using System;
using System.Collections.Generic;

namespace BJoin.Application.WebApi.Validation
{
    public class SortDtoValidation<T> : AbstractValidator<string[]>
    {
        private readonly T _instance;
        public SortDtoValidation()
        {
            _instance = (T)Activator.CreateInstance(typeof(T));
            CascadeMode = CascadeMode.Stop;
            RuleFor(x => x).Must(MatchProperties).WithMessage("自定义排序名称不存在或未正确指定顺序，请检查！");
        }

        private bool MatchProperties(string[] sorts)
        {
            bool result = true;
            if (sorts==null || !sorts.IsAny())
                return result;
            IList<string> sortDtos = new List<string>();
            foreach (string s in sorts)
            {
                sortDtos.Add(s.Replace("-",string.Empty).Replace("+",string.Empty));
            }
            if (sortDtos.IsAny())
            {
                foreach (string sort in sortDtos)
                {
                    if (!_instance.PropertyExist(sort))
                    {
                        result = false;
                        break;
                    }
                }
            }
            return result;
        }
    }
}
